﻿using System;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
using Logger4net;
using MS.Internal.Mita.Foundation;
using MS.Internal.Mita.Foundation.Collections;


namespace UIAStudio
{
    public class PopulationWorkItem : WorkItem
    {
        private UIATreeNode _treeNode;
        private UICondition _condition;
        private int _depth;

        public PopulationWorkItem(WorkQueue queue, UIATreeNode treeNode)
            : this(queue, treeNode, 1, null)
        {
        }

        public PopulationWorkItem(WorkQueue queue, UIATreeNode treeNode, int depth, UICondition condition)
            : base(queue)
        {
            int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
            _treeNode = treeNode;
            _depth = depth;
            _condition = condition;
        }

        public override void Execute()
        {
            UIObject uiItem = _treeNode.UIObject;
            UICollection<UIObject> uiChildren = new UIChildren<UIObject>(uiItem, UIObject.Factory);
            List<UIObject> children = new List<UIObject>();
            foreach (UIObject c in uiChildren)
            {
                children.Add(c);
            }

            ThreadStart threadStart = delegate
            {
                _treeNode.Nodes.Clear();

                foreach (UIObject item in children)
                {

                    UIATreeNode node = new UIATreeNode(item);
                    Logger.Instance.Info("Add node:{0}", UIATreeNode.GetNodeName(item));
                    _treeNode.Nodes.Add(node);
                    if (item.FirstChild != null)
                    {
                        Logger.Instance.Info("Node above has child");
                        node.Nodes.Add("");
                    }
                    
                    if (_depth != 1)    // add +, make it expandable
                    {
                        PopulationWorkItem populate = new PopulationWorkItem(Queue, node, _depth - 1, _condition);
                        Queue.Enqueue(populate);
                    }
                }

            };

            _treeNode.TreeView.Invoke(threadStart);

        }

        private string GetNodeName(UIObject uiItem)
        {
            string name = uiItem.Name;
            string className = uiItem.ClassName;
            return String.Format("\"{0}\" - {1}", name, className);
        }
    }
}
